package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sky.constant.JwtClaimsConstant;
import com.sky.constant.MessageConstant;
import com.sky.dto.UserLoginDTO;
import com.sky.entity.User;
import com.sky.exception.UserNotLoginException;
import com.sky.mapper.UserMapper;
import com.sky.properties.JwtProperties;
import com.sky.properties.WeChatProperties;
import com.sky.service.UserService;
import com.sky.utils.HttpClientUtil;
import com.sky.utils.JwtUtil;
import com.sky.vo.UserLoginVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
public class UserServiceImpl implements UserService {

    @Autowired
    private JwtProperties jwtProperties;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private WeChatProperties weChatProperties;

    public final static String WX_LOGIN = "https://api.weixin.qq.com/sns/jscode2session";

    /**
     * 微信用户登录
     *
     * @param userLoginDTO
     * @return
     */
    @Override
    public UserLoginVO wxLogin(UserLoginDTO userLoginDTO) {
        UserLoginVO userLoginVO = new UserLoginVO();
        Map claims = new HashMap();
        //根据微信授权码code获取用户的唯一标识openid
        String openId = getOpenID(userLoginDTO.getCode());
        //判断openId是否为空，是的话就抛出未登录的异常
        if (openId == null) {
            throw new UserNotLoginException(MessageConstant.USER_NOT_LOGIN);
        }
        //根据openId查询数据库是否有这个用户,没有就直接注册
        User user = userMapper.selectUserByOpenId(openId);
        String token;
        if (user == null) {
            //查出来用户不存在的情况
            /*这里一定要对user初始化！！！！！！！！！！！*/
            user = new User();
            user.setOpenid(openId);
            user.setCreateTime(LocalDateTime.now());
            //用户id的插入回显
            Long userId = userMapper.insert(user);
            claims.put(JwtClaimsConstant.USER_ID, userId);
            token = JwtUtil.createJWT(jwtProperties.getUserSecretKey(), jwtProperties.getUserTtl(), claims);
            //把需要的数据封装进UserLoginVO对象
            userLoginVO.setId(userId);
            userLoginVO.setOpenid(openId);
            userLoginVO.setToken(token);
        } else {
            //如果查出来用户存在的情况
            BeanUtils.copyProperties(user, userLoginVO);
            Long userId = user.getId();
            claims.put(JwtClaimsConstant.USER_ID, userId);
            token = JwtUtil.createJWT(jwtProperties.getUserSecretKey(), jwtProperties.getUserTtl(), claims);
            userLoginVO.setToken(token);
        }
        log.info("返回给Controller的userLoginVO里面的参数为：{}", userLoginVO);
        return userLoginVO;

    }

    /**
     * 根据微信识别码获取用户的唯一标识openid
     *
     * @param code
     * @return
     */
    private String getOpenID(String code) {
//        封装请求参数
        Map map = new HashMap();
        map.put("appid", weChatProperties.getAppid());
        map.put("secret", weChatProperties.getSecret());
        map.put("js_code", code);
        map.put("grant_type", "authorization_code");

        //调用工具类，向微信的接口发送请求
        String json = HttpClientUtil.doGet(WX_LOGIN, map);
        log.info("微信登录的返回结果： {}", json);

        //解析json字符串
        JSONObject jsonObject = JSON.parseObject(json);
        String openid = jsonObject.getString("openid");
        log.info("获取到的用户的openid为{}", openid);
        return openid;
    }

}
